package com.leonzhangxf.server.service;

import com.leonzhangxf.common.JSONSerializer;
import com.leonzhangxf.common.RpcRequest;
import com.leonzhangxf.common.Serializer;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Method;

/**
 * 自定义的业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    private ApplicationContext applicationContext;

    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    private Serializer serializer = new JSONSerializer();

    //当客户端读取数据时,该方法会被调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf byteBuf = (ByteBuf) msg;
        byte[] bytes = new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(bytes);
        RpcRequest rpcRequest = serializer.deserialize(RpcRequest.class, bytes);
        if (null == rpcRequest) {
            // ctx.writeAndFlush("failed");
            return;
        }

        Class<?> aClass = Class.forName(rpcRequest.getClassName());
        Method method = aClass.getMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
        Object bean = applicationContext.getBean(aClass);
        Object result = method.invoke(bean, rpcRequest.getParameters());
        ctx.writeAndFlush(result);
    }

    //创建一个方法启动服务器
    public static void startServer(ApplicationContext applicationContext) throws InterruptedException {
        //1.创建两个线程池对象
        NioEventLoopGroup bossGroup = new NioEventLoopGroup();
        NioEventLoopGroup workGroup = new NioEventLoopGroup();

        //2.创建服务端的启动引导对象
        ServerBootstrap serverBootstrap = new ServerBootstrap();

        //3.配置启动引导对象
        serverBootstrap.group(bossGroup, workGroup)
            //设置通道为NIO
            .channel(NioServerSocketChannel.class)
            //创建监听channel
            .childHandler(new ChannelInitializer<NioSocketChannel>() {
                @Override
                protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
                    //获取管道对象
                    ChannelPipeline pipeline = nioSocketChannel.pipeline();
                    //给管道对象pipeLine 设置编码
                    pipeline.addLast(new StringEncoder());
                    // pipeline.addLast(new RpcDecoder(RpcRequest.class, new JSONSerializer()));
                    //把我们自顶一个ChannelHander添加到通道中
                    UserServiceHandler userServiceHandler = new UserServiceHandler();
                    userServiceHandler.setApplicationContext(applicationContext);
                    pipeline.addLast(userServiceHandler);
                }
            });

        //4.绑定端口
        serverBootstrap.bind(8999).sync();
    }
}
